<template>
    <div class="audience-list">
        <el-form :inline="true" :model="searchParams" class="search">
            <el-form-item label="信息">
                <el-input v-model="searchParams.info" placeholder="查询姓名、手机号、邮箱"></el-input>
            </el-form-item>
            <el-form-item label="加入时间">
                <el-date-picker
                    v-model="searchParams.createTmRange"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="mini" class="search-btn" @click="submitSearch">查询</el-button>
            </el-form-item>
        </el-form>

        <div class="operate-part">
            <!--<el-switch v-model="" active-color="#13ce66" inactive-color="#ff4949"></el-switch>-->            <el-button type="danger" @click="openAddWhiteList">添加白名单</el-button>
            <el-button @click="openImportWhiteList">导入</el-button>
            <el-button @click="batchDelWhiteList">批量移除白名单</el-button>
            <el-button type="text" @click="selectAll">全选</el-button>
            <el-button type="text" @click="selectReserve">反选</el-button>
            <el-button type="text" @click="clear">清除</el-button>
        </div>

        <div class="data-list" v-if="totalCount > 0">
            <el-table
                ref="multipleTable"
                :data="whiteListData"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="tel" label="手机" width="120"></el-table-column>
                <el-table-column prop="mail" label="邮箱" width="120"></el-table-column>
                <el-table-column label="其他信息" width="200">
                  <template slot-scope="scope">
                    <el-tag style="margin:10px" v-for="(other,index) in scope.row.others" :key="index" type='success' disable-transitions>{{other.label}}:{{other.value}}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="加入时间" width="200"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button type="danger" @click="delWhiteList(scope.row.id)">移出白名单</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-pagination
            v-if="totalCount > 0"
            class="pagination-part"
            background
            @current-change="flipPage"
            :current-page.sync="searchParams.currentPage"
            :page-size="pageSize"
            layout="prev, pager, next"
            :total="totalCount"
        ></el-pagination>

        <div class="no-data" v-if="totalCount === 0">
            <img :src="noDataImg" alt="无数据" />
            <div>没有找到符合条件的数据，换个条件试试</div>
        </div>

        <modal
            :visible="isOpenAddWhiteList"
            :width="650"
            @close="closeAddWhiteList"
            class="data-modal"
            title="添加白名单"
        >
            <div class="content">
                <el-form :model="whiteListModel" ref="whiteListForm" label-width="80px">
                    <el-form-item
                        style="width:295px"
                        v-for="item in whiteListForms"
                        :key="item.id"
                        :prop="item.key"
                        :rules="item.rules"
                        :label="item.labelName"
                    >
                        <el-input
                            v-if="item.type ==='input'"
                            maxlength="50"
                            v-model.trim="whiteListModel[item.key]"
                        ></el-input>
                        <el-select
                            v-else-if="item.type === 'selected'"
                            v-model="whiteListModel[item.key]"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="(option,index) in item.options"
                                :key="index"
                                :label="option.label"
                                :value="option.label"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="content-footer">
                    <el-button type="primary" plain @click="saveWhiteList">保存</el-button>
                    <el-button type="primary" plain @click="closeAddWhiteList">关闭</el-button>
                </div>
            </div>
        </modal>

        <modal
            :visible="isOpenImportWhiteList"
            :width="850"
            @close="closeImportWhiteList"
            class="data-modal"
            title="导入白名单"
        >
            <div class="content">
                <el-row type="flex" justify="space-between">
                    <el-col :span="12">
                        <el-card shadow="always" style="height:300px;">
                            <h1>1.下载模板</h1>
                            <p>下载模板后请不要对模板中格式进行改动，以防上传后数据缺失或者失败</p>
                            <el-button
                                style="margin:90px"
                                type="primary"
                                @click="downLoadTemplete"
                            >下载模板</el-button>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card shadow="always" style="height:300px;">
                            <h1>2.导入模板</h1>
                            <div>
                                <p>姓名为必填，一般来说必须有两个字段才能判断用户的真实性，如果不需要验证某些字段则留空</p>
                                <a>帮助</a>
                            </div>
                            <el-upload
                                ref="upload"
                                action="/wm/upload/"
                                :show-file-list="false"
                                :on-change="importTemplete"
                                :auto-upload="false">
                                <el-button style="margin: 65px 90px"
                                    slot="trigger"
                                    icon="el-icon-upload"
                                    type="primary">导入模板</el-button>
                            </el-upload>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </modal>
    </div>
</template>

<script>
import avatarImg from '@/assets/imgs/fj.jpg';
import noDataImg from '@/assets/imgs/no_data/no_data.png';
import moment from 'moment';
import XLSX from 'xlsx';
import { validTel, validMail } from '@/utils/validate'
import { deepCopy } from '@/utils/util'

let checkPhone = (rule, value, callback) => {
    if (!validTel(value)){
        callback(new Error('请输入正确的手机号码'))
    }else {
        callback()
    }
};
export default {
    name: 'audienceWhiteList',
    data() {
        return {
            sceneId:this.$route.query.sceneId,
            noDataImg: noDataImg,
            pageSize: 16,
            totalCount: 1,
            // 搜索参数
            searchParams: {
                isOpen: false,
                info: '',
                createTmRange: [],
                currentPage: 1,
            },
            whiteListData: [], //table分页数据
            whiteListForms: [], //白名单的动态表单
            whiteListModel: {},
            isOpenAddWhiteList: false,
            isOpenImportWhiteList: false,
        };
    },

    mounted() {
        this.queryWhiteListForms();
        this.queryWhiteListByPage();
    },
    methods: {
        /**
         * 分页查询白名单数据
         */
        queryWhiteListByPage(){
            let params = {};
            params.info = this.searchParams.info;
            params.pageIndex = this.searchParams.currentPage;
            let createTmRange = this.searchParams.createTmRange;
            if(createTmRange !=null && createTmRange.length > 0){
                params.startTm = createTmRange[0];
                params.endTm = createTmRange[1];
            }else{
                params.startTm = null;
                params.endTm = null;
            }
            params.sceneId = this.sceneId;
            params.pageSize = this.pageSize;
            this.$api.post('/whiteList/queryByPage',params,
            res => {
                if (res) {
                    let resultArr = [];
                    res.result.forEach(item=>{
                        let others = JSON.parse(item.others)
                        let createTm = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss');
                        item.others = others;
                        item.createTime = createTm;
                        resultArr.push(item);
                    });
                    this.whiteListData = resultArr;
                    this.totalCount = res.totalCount;
                }
            },
            fal => {
                this.$message.error(fal);
            });
        },
        /**
         * 查询白名单表单数据
         */
        queryWhiteListForms(){
            this.$api.get('/whiteList/queryCfg',{sceneId: this.sceneId},
            res => {
                if(res.length >0){
                    res.forEach(item=>{
                        if(item.key ==='tel' && item.rules.length == 2){
                            let validate = { trigger: 'blur', validator: checkPhone }
                            item.rules[1] = validate;
                        }
                    });
                }
                this.whiteListForms = res;
            },
            fal => {
                this.$message.error(fal);
            });
        },
        //打开添加白名单弹窗
        openAddWhiteList() {
            if(this.whiteListForms.length == 0 ){
                this.$message.error("表单模板数据为空");
                return false;
            }
            this.isOpenAddWhiteList = true;
        },
        /**
         * 关闭添加白名单窗口
         */
        closeAddWhiteList() {
            this.$refs.whiteListForm.resetFields();
            this.isOpenAddWhiteList = false;
            this.whiteListModel = {};
        },
        /**
         * 保存白名单数据
         */
        saveWhiteList() {
            this.$refs.whiteListForm.validate(valid => {
                if (valid) {
                    let params = {};
                    params.sceneId = this.sceneId;
                    params.name = this.whiteListModel.name;
                    delete this.whiteListModel.name
                
                    params.tel = this.whiteListModel.tel;
                    delete this.whiteListModel.tel
                
                    params.mail = this.whiteListModel.mail;
                    delete this.whiteListModel.mail
                  
                    console.log("this.whiteListModel",this.whiteListModel);
                    let others = [];
                    this.whiteListForms.forEach(item=>{
                        let key = item.key;
                        let flag = this.whiteListModel.hasOwnProperty(key);
                        if(flag){
                            let other = {};
                            other.label = item.labelName;
                            other.value = this.whiteListModel[key];
                            others.push(other);
                        }
                    })
                    params.others = JSON.stringify(others);
                    console.log('params',params);
                    this.$api.post('/whiteList/add',params,
                    res => {
                        this.$message({message: '操作成功',type: 'success',});
                        this.closeAddWhiteList();
                        this.queryWhiteListByPage();
                    },
                    fal => {
                        this.$message.error(fal);
                    }); 
                } else {
                    return false;
                }
            });
        },
        /**
         * 打开导入excel白名单弹窗
         */
        openImportWhiteList() {
            if(this.whiteListForms.length == 0 ){
                this.$message.error("表单模板数据为空");
                return false;
            }
            this.isOpenImportWhiteList = true;
        },
        /**
         * 关闭导入excel白名单弹窗
         */
        closeImportWhiteList() {
            this.isOpenImportWhiteList = false;
        },
        /**
         * 下载模板
         */
        downLoadTemplete() {
            if(this.whiteListForms.length == 0 ){
                this.$message.error("表单模板数据为空");
                return false;
            }
            //let downLoadData = [["姓名","手机","邮箱","地址"]];
            let downLoadData = [];
            this.whiteListForms.forEach(item=>{
                let labelName = item.labelName;
                downLoadData.push(labelName);
            })
            let time = moment().format('YYYY-MM-DD_HH-mm-ss');
            let fileName = "白名单模板"+ time;
            const ws = XLSX.utils.aoa_to_sheet([downLoadData])
            ws['!cols'] =[{wch: 30}, {wch: 30},{wch: 30},{wch: 30}];  //设置字段宽度
            const wb = XLSX.utils.book_new()
            XLSX.utils.book_append_sheet(wb, ws, fileName);
            /* generate file and send to client */
            XLSX.writeFile(wb, fileName + ".xlsx")
        },
        /**
         * 导入模板
         */
        importTemplete(file) {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            if(!file.name){
                loading.close();
                this.$message.warning('读取不到文件名！');
                return false;
            }
            let fileName = file.name;
            let suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length);
            if("xlsx" !== suffix){
                loading.close();
                this.$message.warning('文件格式不匹配！');
                return false;
            }
            const fileReader = new FileReader();
            fileReader.readAsBinaryString(file.raw);
            fileReader.onload = (ev) => {
                try {
                    const data = ev.target.result;
                    const workbook = XLSX.read(data, {
                        type: 'binary'
                    });
                    this.resolveExcel(loading,workbook);
                } catch (e) {
                    console.error(e)
                    loading.close();
                    this.$message.warning('文件类型不正确！');
                    return false;
                }
            };
        },
        /**
         * 解析excel为json
         */
        resolveExcel(loading,workbook){
            for (let sheet in workbook.Sheets) {
                const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet],{blankrows:true,defval:''});
                console.info("sheetArray",sheetArray);
                if (sheetArray.length <= 0) {
                    loading.close();
                    this.$message.error('文件字段内容为空')
                    return false;
                }
                let params = [];
                for(let i = 0; i < sheetArray.length;i++){
                    let item = sheetArray[i];
                    let objKeys = Object.keys(item);
                    let param = {};
                    let others = [];
                    for(let j =0;j<objKeys.length;j++ ){
                        let form = this.whiteListForms[j];
                        let key = form.key;
                        let labelName = form.labelName;
                        let rules = form.rules;
                        let keyArr = ['tel','mail','name'];
                        if(keyArr.includes(key)){
                            param[key] = item[labelName];
                        }else{
                            let other = {};
                            other.label = labelName;
                            other.value = item[labelName];
                            others.push(other);
                        }
                        console.log('item[labelName]',item[labelName]);
                        if(labelName != objKeys[j]){
                            loading.close();
                            this.$message.error('表头字段不匹配或者调整了模板字段位置')
                            return false;
                        }
                        //rules不为空
                        if(rules){
                            if(rules.length == 1 && !item[labelName]){
                                loading.close();
                                this.$message.error(`第${i+1}行的${labelName}不能为空!`);
                                return false;
                            }
                            if(rules.length == 2 && item[labelName]){
                                if(key === 'tel' && !validTel(item[labelName])){
                                    loading.close();
                                    this.$message.error("请填写正确手机号!");
                                    return false;
                                }
                                if(key ==='mail' && !validMail(item[labelName])){
                                    loading.close();
                                    this.$message.error("请填写正确邮箱!");
                                    return false;
                                }
                            }
                        }
                    }
                    param.others = JSON.stringify(others);
                    param.sceneId = this.sceneId;
                    params.push(param);
                }
                console.log('params',params);
                loading.close();
                this.$api.post('/whiteList/batchAdd',params,
                res => {
                    console.log(res);
                    this.$message({message: '操作成功',type: 'success',});
                    this.closeImportWhiteList();
                    this.queryWhiteListByPage();
                },
                fal => {
                    this.$message.error(fal);
                }); 
            }         
        },
        /**
         * 处理批量添加的参数及校验
         */
        handleBatchAddParams(sheetArray,loading){

        },
        handleSelectionChange(){},
        /**
         * 全选
         */
        selectAll() {
           this.$refs.multipleTable.toggleAllSelection();
        },
        /**
         * 反选
         */
        selectReserve() {
            let allData = this.$refs.multipleTable.data;
            let selectionData = deepCopy(this.$refs.multipleTable.selection);
            //如果当前选中的为0，则是全选
            if(selectionData.length == 0){
                this.selectAll();
            }else{
                let checked = [];
                let map = new Map();
                allData.forEach(row=>{
                    map.set(row.id,row);
                });
                selectionData.forEach(row=>{
                    if(map.has(row.id)){
                        this.$refs.multipleTable.toggleRowSelection(map.get(row.id),false);
                        map.delete(row.id);
                    }
                    
                })
                for (let row of map.values()) {
                    this.$refs.multipleTable.toggleRowSelection(row,true);
                }
            }
        },
        /**
         * 清除用户选择
         */
        clear() {
            this.$refs.multipleTable.clearSelection();
        },
        /**
         * 搜索
         */
        submitSearch() {
            console.log('this.searchParams',this.searchParams);
            this.searchParams.currentPage = 1;
            this.queryWhiteListByPage();
        },

        /**
         * 翻页
         */
        flipPage(val) {
            this.searchParams.currentPage = val;
            this.queryWhiteListByPage();
        },
        /**
         * 移出白名单
         */
        delWhiteList(id){
            this.$api.get('/whiteList/del',{id:id},
            res => {
                this.$message({message: '操作成功',type: 'success',});
                this.queryWhiteListByPage();
            },
            fal => {
                this.$message.error(fal);
            }); 
        },
        /**
         * 批量移除白名单
         */
        batchDelWhiteList(){
            let selectionData = this.$refs.multipleTable.selection;
            if(selectionData.length == 0){
                this.$message.error("请选择白名单!");
                return false;
            }
            let ids = [];
            selectionData.forEach(item=>{
                ids.push(item.id);
            });
            this.$api.post('/whiteList/batchDel',ids,
            res => {
                this.$message({message: '操作成功',type: 'success',});
                this.queryWhiteListByPage();
            },
            fal => {
                this.$message.error(fal);
            }); 
        }
    },
};
</script>

<style lang="scss">
.audience-list {
    width: 100%;
    height: 100%;

    .el-button--text {
        &:hover span {
            text-decoration: underline;
        }
    }

    .search {
        border-bottom: 1px solid #ccc;
        .el-date-editor .el-range-separator {
            min-width: 24px;
        }
    }

    .operate-part {
        margin: 30px 0;
    }

    .data-list {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        flex-direction: row;
        flex-wrap: wrap;
    }

    .pagination-part {
        text-align: center;
    }

    .data-modal {
        .content {
            padding: 20px;
            .content-footer {
                text-align: center;
                margin-top: 40px;
                .el-button {
                    padding-left: 30px;
                    padding-right: 30px;
                }
            }
        }
    }

    .no-data {
        display: flex;
        padding: 20px;
        margin: 20px;
        flex-direction: column;
        align-items: center;

        img {
            width: 200px;
        }

        div {
            font-size: 14px;
            color: #bbb;
            margin-top: 20px;
        }
    }
}
</style>